/**
 * 通知详情页面逻辑
 */

const { ipcRenderer } = require('electron');
const log = require('electron-log');
const { formatDate } = require('../utils/common');

let currentNotification = null;

// 页面初始化
window.addEventListener('DOMContentLoaded', () => {
  log.info('通知详情页面初始化');
  
  // 绑定事件
  bindEvents();
  
  // 加载通知详情
  loadNotificationDetail();
});

// 绑定事件
function bindEvents() {
  // 关闭按钮
  document.getElementById('closeBtn')?.addEventListener('click', () => {
    window.close();
  });

  // 标记已读按钮
  document.getElementById('markReadBtn')?.addEventListener('click', () => {
    if (currentNotification) {
      markAsRead();
    }
  });
}

// 加载通知详情
async function loadNotificationDetail() {
  try {
    // 从URL参数获取通知ID和数据
    const urlParams = new URLSearchParams(window.location.search);
    const notificationId = urlParams.get('id');
    
    if (!notificationId) {
      showError('未找到通知ID');
      return;
    }

    // 优先从URL参数中读取数据（主进程传递）
    const dataParam = urlParams.get('data');
    if (dataParam) {
      try {
        const detailData = JSON.parse(decodeURIComponent(dataParam));
        currentNotification = detailData;
        renderDetail(currentNotification);
        log.info('从URL参数加载通知详情:', notificationId);
        return;
      } catch (e) {
        log.warn('解析URL参数数据失败:', e);
      }
    }

    // 从临时存储读取（base.js传递的数据）
    const currentDetailStr = localStorage.getItem('currentNotificationDetail');
    if (currentDetailStr) {
      try {
        const detailData = JSON.parse(currentDetailStr);
        if (detailData.id === notificationId) {
          currentNotification = detailData;
          localStorage.removeItem('currentNotificationDetail'); // 清除临时数据
          renderDetail(currentNotification);
          log.info('从localStorage加载通知详情:', notificationId);
          return;
        }
      } catch (e) {
        log.warn('解析临时通知数据失败:', e);
      }
    }

    // 回退：从localStorage的appNotifications加载
    const saved = localStorage.getItem('appNotifications');
    if (!saved) {
      showError('未找到通知数据');
      return;
    }

    const notifications = JSON.parse(saved);
    currentNotification = notifications.find(n => n.id === notificationId);

    if (!currentNotification) {
      showError('通知不存在');
      return;
    }

    // 渲染通知详情
    renderDetail(currentNotification);
    log.info('从appNotifications加载通知详情:', notificationId);
  } catch (error) {
    log.error('加载通知详情失败:', error);
    showError('加载失败: ' + error.message);
  }
}

// 渲染通知详情
function renderDetail(notification) {
  const container = document.getElementById('detailContent');
  if (!container) return;

  const typeLabels = {
    info: '信息',
    success: '成功',
    warning: '警告',
    error: '错误'
  };

  const typeLabel = typeLabels[notification.type] || '信息';
  const readStatus = notification.read ? '已读' : '未读';
  
  // 优先级标签
  const priorityLabels = {
    urgent: '紧急',
    high: '高',
    normal: '普通',
    low: '低'
  };
  
  const priority = notification.priority || 'normal';
  const priorityLabel = priorityLabels[priority] || '普通';

  log.info('渲染通知详情:', {
    id: notification.id,
    imageUrl: notification.imageUrl,
    notificationType: notification.notificationType
  });

  // 构建图片HTML
  let imageHtml = '';
  if (notification.imageUrl && (notification.notificationType === 'image' || notification.notificationType === 'both')) {
    imageHtml = `
      <div class="notification-image-container">
        <img src="${notification.imageUrl}" 
             alt="通知图片" 
             onerror="this.style.display='none'"
             onclick="window.open('${notification.imageUrl}', '_blank')">
      </div>
    `;
  }

  container.innerHTML = `
    <div class="notification-title-large">${notification.title}</div>
    <div class="notification-meta">
      <div class="meta-item">
        <span>${formatDate(notification.timestamp)}</span>
      </div>
      <div class="meta-item">
        <span>${readStatus}</span>
      </div>
      <div class="meta-item">
        <span>ID: ${notification.id}</span>
      </div>
      <span class="priority-badge priority-${priority}">${priorityLabel}</span>
    </div>
    ${imageHtml}
    <div class="notification-message-large">${notification.message}</div>
  `;

  // 更新按钮状态
  const markReadBtn = document.getElementById('markReadBtn');
  if (markReadBtn) {
    if (notification.read) {
      // 已读状态：隐藏按钮
      markReadBtn.style.display = 'none';
    } else {
      // 未读状态：显示按钮
      markReadBtn.style.display = 'block';
      markReadBtn.textContent = '标记已读';
      markReadBtn.disabled = false;
      markReadBtn.style.opacity = '1';
      markReadBtn.style.cursor = 'pointer';
    }
  }
}

// 标记为已读
async function markAsRead() {
  try {
    if (currentNotification.read) {
      return; // 已经是已读状态
    }
    
    // 尝试通过IPC标记服务器通知为已读
    try {
      await ipcRenderer.invoke('mark-notification-read', parseInt(currentNotification.id), true);
      log.info('服务器通知已标记为已读:', currentNotification.id);
    } catch (ipcError) {
      log.warn('IPC标记已读失败，尝试本地方式:', ipcError);
      
      // 回退到本地localStorage方式
      const saved = localStorage.getItem('appNotifications');
      if (saved) {
        const notifications = JSON.parse(saved);
        const notification = notifications.find(n => n.id === currentNotification.id);
        
        if (notification && !notification.read) {
          notification.read = true;
          localStorage.setItem('appNotifications', JSON.stringify(notifications));
        }
      }
    }
    
    currentNotification.read = true;
    renderDetail(currentNotification);
    
    // 通知主窗口刷新通知列表
    ipcRenderer.send('notification-updated');
  } catch (error) {
    log.error('标记已读失败:', error);
    alert('操作失败: ' + error.message);
  }
}

// 显示错误
function showError(message) {
  const container = document.getElementById('detailContent');
  if (!container) return;

  container.innerHTML = `
    <div class="empty-state">
      <div>${message}</div>
    </div>
  `;
}
